package com.atguigu.spzx.service.interceptor;

import com.alibaba.fastjson2.JSON;
import com.atguigu.spzx.model.entity.user.UserInfo;
import com.atguigu.spzx.service.utils.AuthContextUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * ClassName: LoginAuthInterceptor
 * Package: com.atguigu.spzx.service.interceptor
 * Description:
 *
 * @Author 刘强
 * @Create 2024/7/16 19:53
 * @Version 1.0
 */
public class UserInfoLoginAuthInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 登陆认证拦截器，用来把用户信息保存到线程本地变量中 AuthContextUtils类
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        // 用户信息一定不为空，因为网关中进行了统一的登陆认证
        String userInfoJson = stringRedisTemplate.opsForValue().get("user:login:"+token);
        AuthContextUtils.set(JSON.parseObject(userInfoJson, UserInfo.class));
        // 直接放行即可
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        AuthContextUtils.remove();
    }
}
